import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class HttpVideoTest extends StatefulWidget {
  const HttpVideoTest({super.key});

  @override
  State<HttpVideoTest> createState() => _HttpVideoTestState();
}

class _HttpVideoTestState extends State<HttpVideoTest> {
  MethodChannel? _methodChannel;
  bool _isLoading = false;
  String _status = '准备测试HTTP视频播放';

  void _onPlatformViewCreated(int viewId) {
    _methodChannel = MethodChannel('native_video_player_$viewId');
    _testHttpVideo();
  }

  Future<void> _testHttpVideo() async {
    if (_methodChannel == null) return;

    setState(() {
      _isLoading = true;
      _status = '正在加载HTTP视频...';
    });

    try {
      final httpUrl = 'http://localhost:18888/123.mp4';
      print('测试HTTP视频播放: $httpUrl');

      await _methodChannel!.invokeMethod('loadVideo', {
        'path': httpUrl,
      });

      setState(() {
        _isLoading = false;
        _status = 'HTTP视频加载成功';
      });

      print('HTTP视频加载成功');
    } catch (e) {
      print('HTTP视频加载失败: $e');
      setState(() {
        _isLoading = false;
        _status = 'HTTP视频加载失败: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        title: const Text('HTTP视频测试'),
      ),
      body: Column(
        children: [
          // 状态显示
          Container(
            padding: const EdgeInsets.all(16),
            child: Text(
              _status,
              style: const TextStyle(color: Colors.white, fontSize: 16),
              textAlign: TextAlign.center,
            ),
          ),
          
          // 加载指示器
          if (_isLoading)
            const CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
            ),
          
          // 视频播放器
          Expanded(
            child: Container(
              color: Colors.black,
              child: AppKitView(
                viewType: 'native_video_player_view',
                onPlatformViewCreated: _onPlatformViewCreated,
                creationParams: {},
                creationParamsCodec: const StandardMessageCodec(),
              ),
            ),
          ),
          
          // 重新测试按钮
          Padding(
            padding: const EdgeInsets.all(16),
            child: ElevatedButton.icon(
              onPressed: _isLoading ? null : _testHttpVideo,
              icon: const Icon(Icons.refresh),
              label: const Text('重新测试'),
            ),
          ),
        ],
      ),
    );
  }
}